package com.spring.activity;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.spring.adapter.AKQInfoAdapter;
import com.spring.gowhere.R;
import com.spring.httputils.RequestParams;
import com.spring.httputils.RestClient;
import com.spring.httputils.TextHttpResponseHandler;
import com.spring.model.TdData;
import com.spring.tool.App;

import org.apache.http.Header;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

public class TDAKQInfoActivity extends BaseActivity {
    private TextView title_tv;
    private PullToRefreshListView xflistview;
    private int mCurrentPage = 1;
    RestClient restClient = null;
    String username = null;
    String logintype = null;
    List<TdData> xfdatalist = null;
    MessageAdapter adapter;
    ImageButton btnBack;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        Log.d("TT", "AKQ....OnCREATE--");
        setContentView(R.layout.td_myxflist);
        xflistview = (PullToRefreshListView) findViewById(R.id.xflistview);
        SharedPreferences userInfo = getSharedPreferences("user_info", 0);
        username = userInfo.getString("username", "");
        logintype = userInfo.getString("logintype", "");
        title_tv = (TextView) findViewById(R.id.title_tv);
        title_tv.setText("通道记录查询");
        btnBack = (ImageButton) findViewById(R.id.title_left_ib);
        btnBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                TDAKQInfoActivity.this.finish();
            }
        });
        // 下拉刷新时的提示文本设置
        xflistview.getLoadingLayoutProxy(true, false).setLastUpdatedLabel("下拉刷新");
        xflistview.getLoadingLayoutProxy(true, false).setPullLabel("");
        xflistview.getLoadingLayoutProxy(true, false).setRefreshingLabel("正在刷新");
        xflistview.getLoadingLayoutProxy(true, false).setReleaseLabel("放开以刷新");
        // 上拉加载更多时的提示文本设置
        xflistview.getLoadingLayoutProxy(false, true).setLastUpdatedLabel("上拉加载");
        xflistview.getLoadingLayoutProxy(false, true).setPullLabel("");
        xflistview.getLoadingLayoutProxy(false, true).setRefreshingLabel("正在加载...");
        xflistview.getLoadingLayoutProxy(false, true).setReleaseLabel("放开以加载");
        xflistview.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<ListView>() {
            @Override
            public void onRefresh(PullToRefreshBase<ListView> refreshView) {
                if (refreshView.isHeaderShown()) {
                    Log.d("", "下拉刷新... ");
                    initPage();
                    loadData(mCurrentPage);

                } else {
                    Log.d("", "上拉加载更多... ");
                    loadData(mCurrentPage);
                }
            }
        });
        xfdatalist = new ArrayList<TdData>();
        adapter = new MessageAdapter(
                TDAKQInfoActivity.this, xfdatalist);
        xflistview.setAdapter(adapter);
        xflistview.setMode(PullToRefreshBase.Mode.BOTH);
        myHandler = new MyHandler();
        loadData(mCurrentPage);
    }

    private void loadData(int index) {
        if (true) {
            restClient = new RestClient(TDAKQInfoActivity.this);
            String url = App.getInstance().url + "/QueryTDList";
            sendHttpDate(url, index);
        }
    }

    private void sendHttpDate(String url, final int index) {

        RequestParams requestparams = new RequestParams(url, "POST");
        requestparams.put("LoginAccount", username);
        requestparams.put("LoginType", logintype);
        requestparams.put("PageCount", "" + 5);
        requestparams.put("PageIndex", "" + index);

        TextHttpResponseHandler textHttpResponseHandler = new TextHttpResponseHandler() {

            @Override
            public void onSuccess(int statusCode, Header[] headers,
                                  String responseString) {
                // TODO Auto-generated method stub
                Log.e("TAG", "mjresponseString---" + responseString);
                try {
                    if (responseString != null && !"".equals(responseString)) {
                        AnalysisData(responseString, index);
                    } else {
                        Toast.makeText(TDAKQInfoActivity.this, "没有查询到相关数据", Toast.LENGTH_SHORT).show();
                    }

                } catch (JSONException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

            }

            @Override
            public void onFailure(int statusCode, Header[] headers,
                                  String responseString, Throwable throwable) {
                // TODO Auto-generated method stub
                Log.e("TAG", "responseString---" + responseString);
                try {
                    AnalysisData(responseString, index);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        };
        try {
            restClient.post(url, requestparams, textHttpResponseHandler);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }


    /**
     * json数据解析
     *
     * @param strResult
     * @throws JSONException
     */
    private void AnalysisData(String strResult, int index) throws JSONException {
        if (index == 1) xfdatalist.clear();
        /**
         * 这里需要分析服务器回传的json格式数据，
         */
        if (strResult != null) {
            JSONObject jsonobject = new JSONObject(strResult);
            JSONArray jsonArray = jsonobject.getJSONArray("ATList");
            if (jsonArray != null && jsonArray.length() > 0) {
                addPage();
                for (int i = 0; i < jsonArray.length(); i++) {
                    JSONObject jsonObject2 = (JSONObject) jsonArray.opt(i);
                    TdData td = new TdData();
                    td.PassWayName = jsonObject2.getString("PassWayName");
                    td.DateTimeBrush = jsonObject2.getString("DateTimeBrush");
                    td.InOutType = jsonObject2.getString("InOutType");
                    xfdatalist.add(td);
                }
            }

        } else {
            Message msg = new Message();
            msg.arg1 = 2;
            TDAKQInfoActivity.this.myHandler.sendMessage(msg); // 向Handler发送消息,更新UI
            return;
        }
        if (xfdatalist != null && xfdatalist.size() > 0) {
            Message msg = new Message();
            msg.arg1 = 1;
            TDAKQInfoActivity.this.myHandler.sendMessage(msg); // 向Handler发送消息,更新UI
        } else {
            Message msg = new Message();
            msg.arg1 = 2;
            TDAKQInfoActivity.this.myHandler.sendMessage(msg); // 向Handler发送消息,更新UI
        }


    }

    MyHandler myHandler;

    private void initPage() {
        mCurrentPage = 1;
    }

    private void addPage() {
        mCurrentPage++;
    }

    /**
     * 接受消息,处理消息 ,此Handler会与当前主线程一块运行
     */

    class MyHandler extends Handler {
        public MyHandler() {
        }

        public MyHandler(Looper L) {
            super(L);
        }

        // 子类必须重写此方法,接受数据
        @Override
        public void handleMessage(Message msg) {
            // TODO Auto-generated method stub
            Log.d("MyHandler", "handleMessage......");
            super.handleMessage(msg);
            // 此处可以更新UI
            switch (msg.arg1) {
                case 1:
                    if (xfdatalist != null && xfdatalist.size() > 0) {

                        xflistview.setVisibility(View.VISIBLE);
                        adapter.notifyDataSetChanged();
                    } else {
                        Toast.makeText(TDAKQInfoActivity.this, "没有查询到相关数据", Toast.LENGTH_SHORT).show();
                    }
                    break;
                case 2:
                    Toast.makeText(TDAKQInfoActivity.this, "无更多数据！", Toast.LENGTH_SHORT).show();
                    break;
                default:
                    break;
            }
            xflistview.onRefreshComplete();
        }
    }

    public class MessageAdapter extends BaseAdapter {

        private LayoutInflater mInflater;
        private List<TdData> returnInfoList;

        public MessageAdapter(Context context, List<TdData> lists) {
            this.mInflater = LayoutInflater.from(context);
            this.returnInfoList = lists;

        }

        @Override
        public int getCount() {
            // TODO Auto-generated method stub
            if (returnInfoList != null && returnInfoList.size() > 0) {
                return returnInfoList.size();
            }
            return 0;
        }

        @Override
        public Object getItem(int position) {
            // TODO Auto-generated method stub
            return position;
        }

        @Override
        public long getItemId(int position) {
            // TODO Auto-generated method stub
            return 0;
        }

        @Override
        public View getView(final int position, View convertView,
                            ViewGroup parent) {
            MessageAdapter.ViewHolder holder = null;
            if (convertView == null) {
                holder = new ViewHolder();
                convertView = mInflater.inflate(R.layout.td_mjlistadapter, null);
                holder.InOutType = (TextView) convertView.findViewById(R.id.txInOutType);
                holder.DateTimeBrush = (TextView) convertView.findViewById(R.id.txDateTimeBrush);
                holder.PassWayName = (TextView) convertView.findViewById(R.id.txPassWayName);

                convertView.setTag(holder);
            } else {
                holder = (MessageAdapter.ViewHolder) convertView.getTag();
            }
            if (returnInfoList != null && returnInfoList.size() > 0) {
                holder.PassWayName.setText(returnInfoList.get(position).PassWayName);
                holder.DateTimeBrush.setText(returnInfoList.get(position).DateTimeBrush);
                holder.InOutType.setText(returnInfoList.get(position).InOutType);

            }

            return convertView;
        }

        public class ViewHolder {
            public TextView PassWayName;
            public TextView DateTimeBrush;
            public TextView InOutType;


        }

    }
}
